﻿using System;
using System.Text.RegularExpressions;
using Sharp.Domain.PlatformBoundedContext.StoragerModule.Aggregates;
using Sharp.Domain.PlatformBoundedContext.UserModule.Services;
using Sharp.Infrastructure.IoC;

namespace Sharp.Domain.PlatformBoundedContext.StoragerModule.Files
{
    internal class DBStorager : IFileStorager
    {
        public string AddOrUpdate(string file)
        {
            if (file.StartsWith("store:"))
            {
                return file;
            }
            var fileStoreRepository = ServiceLocator.Instance.GetService<IFileStoreRepository>();
            var md5 = file.Md5();
            var old = fileStoreRepository.Get(x => x.FileMd5 == md5);
            if (old != null)
            {
                return $"store:DB;id={old.Id}";
            }
            var fileStore = new FileStore()
            {
                FileMd5 = md5,
                FileString = file
            };
            fileStoreRepository.Add(fileStore);
            fileStoreRepository.Context.Commit();

            return $"store:DB;id={fileStore.Id}";
        }


        public string Get(string protocol)
        {
            if (protocol.IsNullOrEmpty())
            {
                return null;
                
            }
            var fileStoreRepository = ServiceLocator.Instance.GetService<IFileStoreRepository>();
            var regex = Regex.Match(protocol, ";id=(\\d+)");
            if (int.TryParse(regex.Groups[1].Value, out var id))
            {
                return fileStoreRepository.Get(id)?.FileString;
            }
             
            return null;
        }
    }
}